package com.xue.action;

import java.net.HttpURLConnection;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;

import org.springframework.http.client.SimpleClientHttpRequestFactory;

/**
 * TLS的三个作用： （1）身份认证 通过证书认证来确认对方的身份，防止中间人攻击 （2）数据私密性
 * 使用对称性密钥加密传输的数据，由于密钥只有客户端/服务端有，其他人无法窥探。 （3）数据完整性
 * 使用摘要算法对报文进行计算，收到消息后校验该值防止数据被篡改或丢失。
 * 
 * 使用RestTemplate进行HTTPS请求访问： private static RestTemplate restTemplate = new
 * RestTemplate(new HttpsClientRequestFactory());
 * 
 */
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
	@Override
	protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
		try {
			if (!(connection instanceof HttpsURLConnection)) {
				throw new RuntimeException("An instance of HttpsURLConnection is expected");
			}

			HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;

			SSLSocketFactory factory = SslTool.getSSLContext("client_trust.jks").getSocketFactory();
			// SSLSocketFactory.getDefault();

			httpsConnection.setSSLSocketFactory(factory);

			httpsConnection.setHostnameVerifier(new HostnameVerifier() {
				@Override
				public boolean verify(String s, SSLSession sslSession) {
					System.out.println("setHostnameVerifier=>" + s);
					return true;
				}
			});

			super.prepareConnection(httpsConnection, httpMethod);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}